package gold.digger;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * Created by fanzhenyu02 on 2020/6/27.
 * common problem solver template.
 */
public class LC851 {
    public long startExecuteTime = System.currentTimeMillis();


    class Solution {
        public int[] loudAndRich(int[][] richer, int[] quiet) {
            int n = quiet.length;
            List<Integer>[] graph = new ArrayList[n];

            for (int i = 0; i < graph.length; i++) {
                graph[i] = new ArrayList<Integer>();
            }

            for (int[] r : richer) {
                graph[r[1]].add(r[0]);
            }

            int[] res = new int[n];
            Arrays.fill(res, -1);

            for (int i = 0; i < n; i++) {
                dfs(graph, res, i, quiet);
            }

            return res;
        }

        private int dfs(List[] graph, int[] res, int cur, int[] quiet) {
            if (res[cur] != -1) {
                return res[cur];
            }

            int ans = cur;
            // dfs 遍历邻居
            for (int next : (List<Integer>) graph[cur]) {
                int nextRicherQuietestIdx = dfs(graph, res, next, quiet);
                if (quiet[nextRicherQuietestIdx] < quiet[ans]) {
                    ans = nextRicherQuietestIdx;
                }
            }

            return res[cur] = ans;
        }
    }

    public void run() {
        Solution solution = new Solution();
        List<Integer> list = new ArrayList<>();
        System.out.println(solution.toString());
    }

    public static void main(String[] args) throws Exception {
        LC851 an = new LC851();
        an.run();

        System.out.println("\ncurrent solution total execute time: " + (System.currentTimeMillis() - an.startExecuteTime) + " ms.");
    }
}
